<?php

namespace app\model;

use think\Model;

class RechargeLimitTemplate extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'recharge_limit_template';
    // 设置当前模型主键
    protected $pk = 'id';

    public function rechargeLimitTemplateCompany()
    {
        return $this->hasMany(RechargeLimitTemplateCompany::class, 'recharge_limit_template_id', 'id');
    }

    public function selectFirstRechargeName(array $fields, string $rechargeName)
    {
        $data = $this->field($fields)->where(['recharge_name' => $rechargeName])->find();

        return $data ? $data->toArray() : [];
    }

    public function selectLimitByIdAndRechargeName(array $fields, int $page, int $limit, int $id, string $rechargeName)
    {
        $where = [];

        if (!empty($id)) {
            $where[] = ['id', '=', $id];
        }

        if (!empty($rechargeName)) {
            $where[] = ['recharge_name', 'like', $rechargeName . '%'];
        }

        return $this->with(['rechargeLimitTemplateCompany' => function ($query) {
            $query->with(['company' => function($query){
                $query->withField(['id', 'name']);
            }])->withField(['recharge_limit_template_id', 'company_id']);
        }])->field($fields)->where($where)->page($page)->limit($limit)->select()->toArray();
    }

    public function selectLimitByIdRechargeNameCount(int $id, string $rechargeName)
    {
        $where = [];

        if (!empty($id)) {
            $where[] = ['id', '=', $id];
        }
        
        if (!empty($rechargeName)) {
            $where[] = ['recharge_name', 'like', $rechargeName . '%'];
        }

        return $this->where($where)->count();
    }

    public function selectFirstById(array $fields, int $id)
    {
        $data = $this->with(['rechargeLimitTemplateCompany' => function ($query) {
            $query->with(['company' => function($query){
                $query->withField(['id', 'name']);
            }])->withField(['recharge_limit_template_id', 'company_id']);
        }])->field($fields)->where(['id' => $id])->find();

        return empty($data) ? [] : $data->toArray();
    }

    public function deleteByid(int $id)
    {
        return $this->where(['id' => $id])->delete();
    }

    // 根据条件获取数据
    public function getDataByWhere($where = [], $fields = 'video_id')
    {
        $data = $this::where($where)->field($fields)->select();
        return $data ? $data->toArray() : [];
    }

    // 根据条件获取一条数据
    public function getInfoByWhere($where = [], $fields = 'recharge_day, recharge_amount')
    {
        $data = $this::where($where)->field($fields)->find();
        return $data ? $data->toArray() : [];
    }
}
